import { EventCard, Player, GameState, Choice } from '../types';

type EventHandler = (data: unknown) => void;

export class EventEngine {
  private eventListeners: Map<string, EventHandler[]> = new Map();
  private chanceCardDeck: EventCard[] = [];
  private communityCardDeck: EventCard[] = [];
  private chanceCardIndex = 0;
  private communityCardIndex = 0;

  /**
   * 初始化事件卡牌组
   */
  initializeDecks(chanceCards: EventCard[], communityCards: EventCard[]): void {
    this.chanceCardDeck = this.shuffleCards([...chanceCards]);
    this.communityCardDeck = this.shuffleCards([...communityCards]);
    this.chanceCardIndex = 0;
    this.communityCardIndex = 0;
  }

  /**
   * 洗牌
   */
  private shuffleCards(cards: EventCard[]): EventCard[] {
    const shuffled = [...cards];
    for (let i = shuffled.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
    }
    return shuffled;
  }

  /**
   * 抽取事件卡
   */
  drawEventCard(type: 'chance' | 'community'): EventCard {
    if (type === 'chance') {
      if (this.chanceCardDeck.length === 0) {
        throw new Error('机会卡牌组为空');
      }
      
      const card = this.chanceCardDeck[this.chanceCardIndex];
      this.chanceCardIndex = (this.chanceCardIndex + 1) % this.chanceCardDeck.length;
      
      // 如果回到开头，重新洗牌
      if (this.chanceCardIndex === 0) {
        this.chanceCardDeck = this.shuffleCards(this.chanceCardDeck);
      }
      
      return card;
    } else {
      if (this.communityCardDeck.length === 0) {
        throw new Error('社区卡牌组为空');
      }
      
      const card = this.communityCardDeck[this.communityCardIndex];
      this.communityCardIndex = (this.communityCardIndex + 1) % this.communityCardDeck.length;
      
      // 如果回到开头，重新洗牌
      if (this.communityCardIndex === 0) {
        this.communityCardDeck = this.shuffleCards(this.communityCardDeck);
      }
      
      return card;
    }
  }

  /**
   * 执行事件
   */
  executeEvent(card: EventCard, player: Player, gameState: GameState): void {
    try {
      // 如果有选择项，不立即执行，等待玩家选择
      if (card.choices && card.choices.length > 0) {
        // 触发事件，UI会处理选择
        this.emit('event:choice-required', {
          card,
          player,
          gameState,
        });
        return;
      }

      // 执行事件效果
      card.effect(player, gameState);
      
      // 触发事件完成
      this.emit('event:executed', {
        card,
        player,
        gameState,
      });
    } catch (error) {
      console.error(`事件执行失败: ${card.title}`, error);
      this.emit('event:error', {
        card,
        player,
        error,
      });
    }
  }

  /**
   * 处理事件选择
   */
  handleChoice(card: EventCard, choiceIndex: number, player: Player, gameState: GameState): void {
    if (!card.choices || choiceIndex < 0 || choiceIndex >= card.choices.length) {
      throw new Error('无效的选择');
    }

    const choice = card.choices[choiceIndex];
    
    try {
      choice.effect(player, gameState);
      
      this.emit('event:choice-made', {
        card,
        choice,
        player,
        gameState,
      });
    } catch (error) {
      console.error(`选择执行失败: ${choice.text}`, error);
      this.emit('event:error', {
        card,
        choice,
        error,
      });
    }
  }

  /**
   * 注册事件监听器
   */
  on(event: string, handler: EventHandler): void {
    if (!this.eventListeners.has(event)) {
      this.eventListeners.set(event, []);
    }
    this.eventListeners.get(event)!.push(handler);
  }

  /**
   * 移除事件监听器
   */
  off(event: string, handler: EventHandler): void {
    const handlers = this.eventListeners.get(event);
    if (handlers) {
      const index = handlers.indexOf(handler);
      if (index !== -1) {
        handlers.splice(index, 1);
      }
    }
  }

  /**
   * 触发事件
   */
  emit(event: string, data: unknown): void {
    const handlers = this.eventListeners.get(event);
    if (handlers) {
      handlers.forEach(handler => {
        try {
          handler(data);
        } catch (error) {
          console.error(`事件处理器执行失败: ${event}`, error);
        }
      });
    }
  }

  /**
   * 清除所有监听器
   */
  clearListeners(): void {
    this.eventListeners.clear();
  }

  /**
   * 获取剩余卡牌数量
   */
  getRemainingCards(type: 'chance' | 'community'): number {
    if (type === 'chance') {
      return this.chanceCardDeck.length - this.chanceCardIndex;
    } else {
      return this.communityCardDeck.length - this.communityCardIndex;
    }
  }
}

// 导出单例实例
export const eventEngine = new EventEngine();
